﻿function Pollutant(container, config) {
    this.timepoints = [];
    this.SO2 = [];
    this.NO2 = [];
    this.NO = [];
    this.CO = [];
    this.O3 = [];
    this.O3_8H = [];
    this.PM25 = [];
    this.PM10 = [];
    this.AQI = [];
    this.AQIRange = [];
    this.AQILevel = [];
    this.PrimaryPollutant = [];


   

    this.series = [];
    this.seriesParam = config["seriesParam"] || [];
    this.height = config["height"] || null;
    this.width = config["width"] || null;
    this.xwidth = config["xwidth"] || null;
    this.title = config["title"] || "";
    this.useDefaultTip = config["useDefaultTip"] || false;
    this.doubleAxis = config["doubleAxis"] || false;
    this.coAxis = config["coAxis"] || false;
    this.yAxis = [];

    this.subtitle = config["subtitle"] || "";

    this.container = container;
}

Pollutant.prototype.tooltipFormatter = function (tooltip) {
    var _ = this;
    if (_.useDefaultTip) {
        var series = tooltip.point.series, point = tooltip.point;
        return series.name + ":" +  _.formatValue(Highcharts.pick(point.value, point.y));
    }
    // Create the header with reference to the time interval
    var index = tooltip.points[0].point.x,
        ret = '<middle>' + tooltip.x + '</middle><br>';

    ret += '<table class="table_tooltip">';

    // Add all series
    var color, name, value, range;
    Highcharts.each(tooltip.points, function (point) {
        var series = point.series;
        if (series.name === "AQI") {
            color = series.color, name = series.name, value = Highcharts.pick(point.point.value, point.y);
        }
        else {
            range = series.yData[index][0] + ',' + series.yData[index][1];
        }
    });
    ret += '<tr><td colspan="5"><span style="color:' + color + '">\u25CF</span> ' + name +
             ':' + value + '（' + (range===undefined?"范围信息暂缺":range) + '）';
    ret += '<tr><td colspan="5">AQI等级: ' + _.AQILevel[index] + '</td></tr>';
    ret += '<tr><td colspan="5">首要污染物: ' +pollutantNameSubTransform(_.PrimaryPollutant[index]) + '</td></tr>';

    ret += '<tr><td width="55px" align="right">SO<sub><span>2</span></sub>:</td><td width="35px" class="color-blue"> ' + this.SO2[index] + '</td><td width="10px">&nbsp;</td><td align="right" width="55px">NO<sub><span>2</span></sub>:</td><td width="35px" class="color-blue"> ' + this.NO2[index] + '</td></tr>' +
        '<tr><td align="right">CO:</td><td class="color-blue" class="color-blue"> ' + this.CO[index] + '</td><td>&nbsp;</td><td align="right">O<sub><span>3</span></sub>:</td><td class="color-blue"> ' + this.O3[index] + '</td></tr>' +
          '<tr><td align="right">PM<sub><span>10</span></sub>:</td><td class="color-blue"> ' + this.PM10[index] + '</td><td>&nbsp;</td><td align="right">PM<sub><span>2.5</span></sub>:</td><td class="color-blue"> ' + this.PM25[index] + '</td></tr>';

    if (this.O3_8H.length != 0) {
        ret += '<tr><td align="right">O<sub>3</sub>_8H: </td><td class="color-blue">' + this.O3_8H[index] + '</td></tr>';
    }
    
    ret += '</table>';

    return ret;
};

Pollutant.prototype.getStep = function () {
    var _ = this,
        width = $("#" + _.container).width(),
        count = _.timepoints.length,
        num = 1,
        xWidth = _.xwidth;
    while (xWidth * count > width) {
        num = num * 2;
        count = count / 2;
    }
    return num;
}

Pollutant.prototype.getChartOptions = function () {
    var pollutant = this, shared = true;
    if (pollutant.useDefaultTip) {
        shared = false;
    }
    return {
        chart: {
            renderTo: pollutant.container,
            height: pollutant.height,
            width: pollutant.width
        },
        title: {
            text: pollutant.title || 'AQI趋势图'
        },
        subtitle: {
            text: pollutant.subtitle,
            x: -20
        },
        credits: {
            enabled: false
        },
        xAxis: [{
            categories: pollutant.timepoints,
            tickInterval: pollutant.getStep()
        }],
        yAxis: pollutant.yAxis,
        tooltip: {
            shared: shared,
            crosshairs: true,
            useHTML: true,
            formatter: function () {
                return pollutant.tooltipFormatter(this);
            }
        },
        series: pollutant.series
    }
};

Pollutant.prototype.onChartLoad = function (chart) {
    if ($("#dataTable").length > 0) {
        $("#dataTable").show();
    }
};

Pollutant.prototype.createChart = function () {
    var pollutant = this;
    this.chart = new Highcharts.Chart(pollutant.getChartOptions(), function (chart) {
        pollutant.onChartLoad(chart);
    });
};


Pollutant.prototype.createNoDataChart = function () {
    var pollutantChart = this;

    var nodataOptions = {
        chart: {
            renderTo: pollutantChart.container,
            height: pollutantChart.height,
            width: pollutantChart.width
        },
        title: {
            text: '暂无数据'
        },
        series: [{
            type: 'line',
            name: 'AQI',
            data: []
        }],
        lang: {
            noData: "Nichts zu anzeigen"
        },
        noData: {
            style: {
                fontWeight: 'bold',
                fontSize: '15px',
                color: '#303030'
            }
        }
    };
    this.chart = new Highcharts.Chart(nodataOptions, function (chart) {
        pollutantChart.onChartLoad(chart);
    });
};



Pollutant.prototype.initData = function (jsonData) {
    var pol = this, axisName;
    if (jsonData.length > 0) {
        for (var i = 0, count = jsonData.length; i < count; i++) {
            pol.timepoints.push(formatDate(GetTimeFromJsonString(jsonData[i].ForTime), "MM月DD日"));
            pol.SO2.push(jsonData[i].SO2);
            pol.NO2.push(jsonData[i].NO2);
            pol.NO.push(jsonData[i].NO);
            pol.CO.push(jsonData[i].CO);
            pol.O3.push(jsonData[i].O3);
            pol.O3_8H.push(jsonData[i].O3_8H);
            pol.PM25.push(jsonData[i].PM2_5);
            pol.PM10.push(jsonData[i].PM10);
            pol.AQI.push(jsonData[i].AQI);
            pol.AQIRange.push([jsonData[i].AQI_Low, jsonData[i].AQI_High])
            pol.PrimaryPollutant.push(jsonData[i].PrimaryPollutant);
            pol.AQILevel.push(jsonData[i].AQILevel);
        }

        pol.series.push({
            id: 'AQILine',
            name: 'AQI',
            type: 'spline',
            data: pol.AQI
        });
        if (pol.AQIRange.length > 0) {//有些页面无范围数据，如监测值页面
            pol.series.push({
                name: 'AQI范围',
                data: pol.AQIRange,
                type: 'arearange',
                lineWidth: 0,
                linkedTo: 'AQILine',
                color: Highcharts.getOptions().colors[0],
                fillOpacity: 0.3,
                zIndex: 0
            });
        }



        if (!pol.doubleAxis && !pol.coAxis) {
            pol.yAxis.push({
                title: {
                    text: null
                },
                labels: {
                    style: {
                        fontSize: '10px'
                    }
                },
                plotLines: levelStandardLine
            });
        }
        else {
            pol.yAxis.push({
                title: {
                    text: axisName
                },
                labels: {
                    style: {
                        fontSize: '10px'
                    }
                },
                tickInterval: 10,
                plotLines: levelStandardLine
            });
            pol.yAxis.push({
                title: {
                    text: "污染物浓度（mg/m3）"
                },
                labels: {
                    style: {
                        fontSize: '10px'
                    }
                },
                opposite: true
            });
        }
        pol.series = pol.getSeries(pol.series);
        pol.createChart();
    }
    else {
        pol.createNoDataChart();
    }
};

Pollutant.prototype.getSeries = function (series) {
    var _ = this, axisIdx = 1, name, disName;
    if (_.seriesParam.length != 0) {
        series = [];
        for (var i = 0; i < _.seriesParam.length; i++) {
            name = _.seriesParam[i];
            disName = _.seriesParam[i]
            if (name === "PM25") {
                disName = "PM2.5";
            }
            if (name === "AQI") {
                axisIdx = 0;
            }
            else {
                axisIdx = 1;
            }
            series.push({
                name: disName,
                type: 'line',
                data: _[name],
                yAxis: axisIdx
            });
        }
    }
    return series;
}

Pollutant.prototype.getAddSeries = function (name) {
    var _ = this, axisIdx = 1, disName = name;
    if (name === "CO" && _.doubleAxis === false) {
        axisIdx = 0;
    }
    else {
        axisIdx = 1;
    }
    if (name === "PM25") {
        disName = "PM2.5";
    }
    var series = {
        name: disName,
        type: 'spline',
        data: _[name],
        yAxis: axisIdx
    };
    return series;
}

Pollutant.prototype.formatValue = function (value, number) {//格式化数据，不四舍五入,params:值和小数位
    if (value && value !== null) {
        value = value.toString();
        var temp = value.split('.'),
            count = number || 3,
            result = (temp[0] || "0");
        if (temp[1]) {
            result += ".";
            for (var i = 0; i < count; i++) {
                result += (temp[1].charAt(i) ? temp[1].charAt(i) : "0");
            }
        }
        return result;
    }
    else {
        return "暂缺";
    }
    return value;
}